package com.imooc.security.demo.intercept;

import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author JackYang
 * @description:
 * @create: 2020/6/13 23:57
 */
@Component
public class TimeInterceptor implements HandlerInterceptor {
    
    /**
     * controller中被调用方法执行之前，先执行preHandle方法
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("-----preHandle.....:");
        //System.out.println("-----"+handler);
        System.out.println("-----获取当前被调用controller bean名称："+((HandlerMethod)handler).getBean().getClass().getName());
        System.out.println("-----获取当前被调用controller 中的方法名称："+((HandlerMethod)handler).getMethod().getName());
        request.setAttribute("startTime", System.currentTimeMillis());
        //只有返回true， controller中被调用方法才能执行
        return true;
    }
    
    /**
     * controller中被调用方法执行之后，再执行postHandle方法
     * 需要注意的时：若controller中被调用方法执行时发生异常，将不会执行postHandle方法
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
        System.out.println("-----postHandle...........");
    }
    
    /**
     * 在postHandle执行完之后，才执行afterCompletion方法。
     * 注意：无论controller中被调用方法执行时是否发生异常，最终都会执行afterCompletion方法
     * 若有异常，Exception ex对象将会携带异常信息，否者Exception ex对象为空
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
        System.out.println("-----afterCompletion");
        System.out.println("-----"+handler);
        if (ex!=null){
            System.out.println("-----"+ex.getMessage());
        }
        long starter= (long) request.getAttribute("startTime");
        System.out.println("-----afterCompletion...........总共耗时："+(System.currentTimeMillis()-starter));
    }
}
